// 数据库模块
const MinioUtils = require('../../uploadTool/minio');
const multer = require('multer');
const fs = require('fs');
const moment = require('moment');

const path = 'public/Images';
if (!fs.existsSync(path)) {
  fs.mkdirSync(path, { recursive: true });
}
const todayDir = moment().format('YYYYMMDD');
if (!fs.existsSync(`${path}/${todayDir}`)) {
  fs.mkdirSync(`${path}/${todayDir}`, { recursive: true });
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, `${path}/${todayDir}`);
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '.' + file.originalname.split('.').pop());
  },
});

// file 指上传图片的 key
var upload = multer({ storage: storage }).single('file');

const uploadFile = async (req, res) => {
  console.log('上传文件');
  try {
    upload(req, res, async err => {
      if (err) {
        return res.json({
          msg: '上传失败',
          errcode: 1,
          msg: err,
          success: false,
        });
      }

      // 开始上传minio
      const { data, success } = await MinioUtils.uploadFileMinio(req.file.filename, req.file.path);
      console.log('上传minio返回数据', success, data);
      res.json({
        msg: success ? '上传成功' : '上传失败',
        errcode: success ? 0 : 1,
        data: success ? data : null,
        success: success,
      });
    });
  } catch (error) {
    return res.json({
      msg: '上传失败',
      errcode: 1,
      success: false,
      msg: error,
    });
  }
};

module.exports = {
  uploadFile,
};
